/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package businessLogic;

import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import persistence.Client;
import persistence.Exemplar;
import persistence.Loan;
import persistence.Medium;

/**
 *
 * @author breinesg
 */

@Stateless
public class LoanMgrBean implements LoanMgr {
    
    @PersistenceContext(unitName = "its_Lib-ejbPU")
    
    private EntityManager em;

    
    @Override
    public Loan loanMedium(int id, String firstName, String lastName) {
        //throw new UnsupportedOperationException("Not supported yet.");
        
        Loan loan = new Loan();
        loan.setExemplarId(id);
        loan.setClientId(searchClient(firstName, lastName));
        loan.setStartDate(new Date());
        em.persist(loan); 
        return loan;
    }

    @Override
    public Exemplar returnMedium(int id) {
        //throw new UnsupportedOperationException("Not supported yet.");
        
        Exemplar var = em.createNamedQuery("Exemplar.findByMediumId", Exemplar.class)
                .setParameter("mediumId", id).getSingleResult();
        System.out.println("Medium " + id + " returned.");
        return var;
    }

    @Override
    public Medium searchMedium(String var) {
        //throw new UnsupportedOperationException("Not supported yet.");
        
        Medium medium = em.createNamedQuery("Medium.findByTitle", Medium.class)
                .setParameter("title", var).getSingleResult();
        
        return medium;
    }

    @Override
    public void reserveMedium(int id) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void cancelReservation(int id) {
          
                System.out.println("Reservation " + id + " cancelt");
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Loan askOwnState(String firstName, String lastName) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    public void persist(Object object) {
        em.persist(object);
    }
    
    
    @Override
    public Client searchClient(String firstName, String lastName) {
        
        return em.createNamedQuery("Client.findByFullName", Client.class)
                    .setParameter("lastName", lastName)
                    .setParameter("firstName", firstName)
                    .getSingleResult();
    }
/*
    public void persist1(Object object) {
        em.persist(object);
    }
 */   

}
